<?php

namespace app\admin\controller\performance;

use app\admin\model\AuthGroup;
use app\admin\model\AuthGroupAccess;
use app\common\controller\Backend;
use fast\Random;
use fast\Tree;
use think\Db;
/**
 * 管理员管理
 *
 * @icon fa fa-users
 * @remark 一个管理员可以有多个角色组,左侧的菜单根据管理员所拥有的权限进行生成
 */
class Admin extends Backend
{

    protected $model = null;
    protected $childrenGroupIds = [];
    protected $childrenAdminIds = [];
    protected $searchFields = 'username';
    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Admin');

        $this->childrenAdminIds = $this->auth->getChildAdminIds(true);//不包含自己同级别部门的
        $this->childrenGroupIds = $this->auth->getChildrenGroupIds(false);//不包含自己部门的

        $groupList = collection(AuthGroup::where('id', 'in', $this->childrenGroupIds)->select())->toArray();

        Tree::instance()->init($groupList);
        $groupdata = [];
        if ($this->auth->isSuperAdmin())
        {
            $result = Tree::instance()->getTreeList(Tree::instance()->getTreeArray(0));
            foreach ($result as $k => $v)
            {
                $groupdata[$v['id']] = $v['name'];
            }
        }
        else
        {
            $result = [];
            $groups = $this->auth->getGroups();
            foreach ($groups as $m => $n)
            {
                $childlist = Tree::instance()->getTreeList(Tree::instance()->getTreeArray($n['id']));
                $temp = [];
                foreach ($childlist as $k => $v)
                {
                    $temp[$v['id']] = $v['name'];
                }
                $result[__($n['name'])] = $temp;
            }
            $groupdata = $result;
        }

        $this->view->assign('groupdata', $groupdata);
        $this->assignconfig("admin", ['id' => $this->auth->id]);
    }
   
    /**
     * 查看
     */
    public function index()
    {
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('pkey_name'))
            {
                return $this->selectpage();
            }
            $childrenGroupIds = $this->childrenGroupIds;
            
            $groupName = AuthGroup::where('id', 'in', $childrenGroupIds)
                    ->column('id,name');
            $authGroupList = AuthGroupAccess::where('group_id', 'in', $childrenGroupIds)
                    ->field('uid,group_id')
                    ->select();

            $adminGroupName = [];
            foreach ($authGroupList as $k => $v)
            {
                if (isset($groupName[$v['group_id']]))
                    $adminGroupName[$v['uid']][$v['group_id']] = $groupName[$v['group_id']];
            }
            $groups = $this->auth->getGroups();
            foreach ($groups as $m => $n)
            {
                $adminGroupName[$this->auth->id][$n['id']] = $n['name'];
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->where($where)
                    ->where('id', 'in', $this->childrenAdminIds)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->where($where)
                    ->where('id', 'in', $this->childrenAdminIds)
                    ->field(['password', 'salt', 'token'], true)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            $groups = model("groupname")->select();        
            $departments = model("department")->select();
            foreach ($groups as $key => $value) 
            {
                $needgroup[$value['id']] = $value['name'];
            }
            foreach ($departments as $key => $value) 
            {
                $needdepratment[$value['id']] = $value['name'];
            }
         
            foreach ($list as $k => $v)
            {
                $groups = isset($adminGroupName[$v['id']]) ? $adminGroupName[$v['id']] : [];
                $list[$k]['groups'] = implode(',', array_keys($groups));
                $list[$k]['groups_text'] = implode(',', array_values($groups));
                if($v['department_id'])
                {   
                    $list[$k]['department_name'] = $needdepratment[$v['department_id']];
                  
                }
                if($v['groupname_id'])
                {   
                    $list[$k]['groupname_name'] = $needgroup[$v['groupname_id']];
                }
              
                $return =$this->checkEvaluation($v['id']);
                $list[$k]['is_month_check'] = $return['status'];
                if(($return['per']))
                {
                    $list[$k]['content'] = $return['per'];
                }
                
                
            }
            foreach ($list as $key => $value) 
            {
                
            }
            $check_status = array_column($list, 'is_month_check');
            if(in_array( '1',$check_status))
            {  
               //是否存在未平存在就不检测 百分比消息
            }else
            {   
                 //并且全部打分完成的时候
                // $this->checkPercent();
            }
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        $this->checkPercent();
        return $this->view->fetch();
    }
    public function checkPercent(){
        $admin_id = $this->auth->id;
        $group = $this->auth->getGroups($admin_id);
        $alluser = $this->childrenAdminIds;

        $arr = array_merge(array_diff($alluser, array($admin_id)));
        $default = model("norm")->find();
        
        # code... 优
        $map1['ave_score'] = array("GT",$default['excellence']);
        $a = $default['bad'];
        $b = $default['excellence'];
        $map2['ave_score'] = array("BETWEEN",[$a,$b]);
        $map3['ave_score'] = array("LT",$default['bad']);

        $excellence = $default['excellence_per'];
        $good = $default['good_per'];
        $bad = $default['bad_per'];
        $where['admin_id'] =  array("in",$arr);//员工
        $where['datekey'] = date("Y").date("m");
        foreach ($group as $key => $value) 
        {  
            if($value['pid'] == '1'||$value['pid'] == '0'){
                //部门领导 或者 超级管理员
                
                $ex_exce = model("performance")->where($map1)->where($where)->count();
                $ex_good = model("performance")->where($map2)->where($where)->count();
                $ex_bad  = model("performance")->where($map3)->where($where)->count();
                $ex_exce_per = $ex_exce/($ex_exce+$ex_good+$ex_bad);
                $ex_good_per = $ex_good/($ex_exce+$ex_good+$ex_bad);
                $ex_bad_per = $ex_bad/($ex_exce+$ex_good+$ex_bad);

                $re_exce = (round($ex_exce_per*100,2)).'%';
                $re_good = (round($ex_good_per*100,2)).'%';
                $re_bad = (round($ex_bad_per*100,2)).'%';
               
                $content="";
                $message = 0;
                if($ex_exce_per>=$excellence){
                    $message = 1;
                    $content = "优比偏大，目前为".$re_exce;
                }
               

                if($ex_bad_per<=$bad){
                    $message = 1;
                    $content = "差比偏小，目前为".$re_bad.";".$content;
                }

                if($message == '1'){
                    //查看是否需要发送消息;
                    $map4['admin_id'] = $admin_id;
                    $map4['datekey'] = date("Y").date("m");
                    $map4['message_type'] = 1;
                    $res = Db::table("message")->where($map4)->find();

                    if(!$res){
                        $map4['title'] = $content;
                        $map4['createtime'] = time();
                        Db::table("message")->insert($map4);
                    }
                }
                // 检测优良好比百分
                
            }
        }
        
    }
    public function checkEvaluation($admin_id){
        $login_id = $this->auth->id;
        if($admin_id == $login_id)
        {
            //自评
            $where['self_score'] = '0';
        }else
        {   //上级评
            $where['superior_score'] = '0';
        }
        $where['admin_id'] = $admin_id;
        $where['month'] = date("m");
        $where['year'] = date("Y");
        $check = model("evaluation")->where($where)->find();
        
        $return['status'] = 1;
        $return['per'] ="";
        if($check)
        {   //有未平
            return $return;
        }else
        {   //已评
            $map['admin_id'] = $admin_id;
            $map['month'] = date("m");
            $map['year'] = date("Y");
            $pin = model("performance")->where($map)->find();
            $default = model("norm")->find();
           
            # code... 优
            $excellence = $default['excellence'];
            if($pin['ave_score']>$excellence){
                $return['status'] = 0;
                $return['per'] = "优";

                return $return;
            }
            $good = $default['good'];
           

            $bad = $default['bad'];
            if($pin['ave_score']<$bad){
                $return['status'] = 0;
                $return['per'] = "差";
                return $return;
            }
             if($pin['ave_score']<=$excellence&&$pin['ave_score']>=$bad){
                $return['status'] = 0;
                $return['per'] = "良";
                return $return;
            }
           
        }
    }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a");
            if ($params)
            {
                $params['salt'] = Random::alnum();
                $params['password'] = md5(md5($params['password']) . $params['salt']);
                $params['avatar'] = '/assets/img/avatar.png'; //设置新管理员默认头像。
                $result = $this->model->validate('Admin.add')->save($params);
                if ($result === false)
                {
                    $this->error($this->model->getError());
                }
                $group = $this->request->post("group/a");

                //过滤不允许的组别,避免越权
                $group = array_intersect($this->childrenGroupIds, $group);
                $dataset = [];
                foreach ($group as $value)
                {
                    $dataset[] = ['uid' => $this->model->id, 'group_id' => $value];
                }
                model('AuthGroupAccess')->saveAll($dataset);
                $this->success();
            }
            $this->error();
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row)
            $this->error(__('No Results were found'));
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a");
            if ($params)
            {
                if ($params['password'])
                {
                    $params['salt'] = Random::alnum();
                    $params['password'] = md5(md5($params['password']) . $params['salt']);
                }
                else
                {
                    unset($params['password'], $params['salt']);
                }
                //这里需要针对username和email做唯一验证
                $adminValidate = \think\Loader::validate('Admin');
                $adminValidate->rule([
                    'username' => 'require|max:50|unique:admin,username,' . $row->id,
                    'email'    => 'require|email|unique:admin,email,' . $row->id
                ]);
                $result = $row->validate('Admin.edit')->save($params);
                if ($result === false)
                {
                    $this->error($row->getError());
                }

                // 先移除所有权限
                model('AuthGroupAccess')->where('uid', $row->id)->delete();

                $group = $this->request->post("group/a");

                // 过滤不允许的组别,避免越权
                $group = array_intersect($this->childrenGroupIds, $group);

                $dataset = [];
                foreach ($group as $value)
                {
                    $dataset[] = ['uid' => $row->id, 'group_id' => $value];
                }
                model('AuthGroupAccess')->saveAll($dataset);
                $this->success();
            }
            $this->error();
        }
        $grouplist = $this->auth->getGroups($row['id']);
        $groupids = [];
        foreach ($grouplist as $k => $v)
        {
            $groupids[] = $v['id'];
        }
        $this->view->assign("row", $row);
        $this->view->assign("groupids", $groupids);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids)
        {
            // 避免越权删除管理员
            $childrenGroupIds = $this->childrenGroupIds;
            $adminList = $this->model->where('id', 'in', $ids)->where('id', 'in', function($query) use($childrenGroupIds) {
                        $query->name('auth_group_access')->where('group_id', 'in', $childrenGroupIds)->field('uid');
                    })->select();
            if ($adminList)
            {
                $deleteIds = [];
                foreach ($adminList as $k => $v)
                {
                    $deleteIds[] = $v->id;
                }
                $deleteIds = array_diff($deleteIds, [$this->auth->id]);
                if ($deleteIds)
                {
                    $this->model->destroy($deleteIds);
                    model('AuthGroupAccess')->where('uid', 'in', $deleteIds)->delete();
                    $this->success();
                }
            }
        }
        $this->error();
    }

    /**
     * 批量更新
     * @internal
     */
    public function multi($ids = "")
    {
        // 管理员禁止批量操作
        $this->error();
    }

    /**
     * 下拉搜索
     */
    protected function selectpage()
    {
        $this->dataLimit = 'auth';
        $this->dataLimitField = 'id';
        return parent::selectpage();
    }

}
